//
//  VCAddPunch.m
//  MOSAD_HW2_1
//
//  Created by Jason on 2016/10/29.
//  Copyright © 2016 Jason. All rights reserved.
//

#import "VCAddPunch.h"

@interface VCAddPunch ()

@end

@implementation VCAddPunch

- (instancetype)init
{
    self = [super init];
    //设置背景颜色
    
    UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"daka.png"]];
    //修改图片大小
    UIGraphicsBeginImageContext(CGSizeMake(32, 32));
    [image drawInRect:CGRectMake(0, 0, 32, 32)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //创建一个分栏按钮对象
    UITabBarItem * tabBarItem = [[UITabBarItem alloc] initWithTitle:@"打卡" image:reSizeImage tag:2];
    
    self.tabBarItem = tabBarItem;
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationItem setTitle:@"添加打卡"];
    
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    for (int i = 0; i < 5; i++) {
        _pictureNum[i] = 0;
    }
    _pictureCount = 0;
    
    
    //时间提示
    _lbTime = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    _lbTime.text = @"时间";
    _lbTime.font = [UIFont systemFontOfSize:18];
    _lbTime.textAlignment = NSTextAlignmentLeft;
    //地点提示
    _lbLocation = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 100, 30)];
    _lbLocation.text = @"地点";
    _lbLocation.font = [UIFont systemFontOfSize:18];
    _lbLocation.textAlignment = NSTextAlignmentLeft;
    //景点名称提示
    _lbScenicSpots = [[UILabel alloc] initWithFrame:CGRectMake(10, 110, 100, 30)];
    _lbScenicSpots.text = @"景点名称";
    _lbScenicSpots.font = [UIFont systemFontOfSize:18];
    _lbScenicSpots.textAlignment = NSTextAlignmentLeft;
    //心得提示
    _lbExperience = [[UILabel alloc] initWithFrame:CGRectMake(10, 160, 100, 30)];
    _lbExperience.text = @"心得";
    _lbExperience.font = [UIFont systemFontOfSize:18];
    _lbExperience.textAlignment = NSTextAlignmentLeft;
    //配图提示
    _lbPictures = [[UILabel alloc] initWithFrame:CGRectMake(10, 370, 100, 30)];
    _lbPictures.text = @"配图";
    _lbPictures.font = [UIFont systemFontOfSize:18];
    _lbPictures.textAlignment = NSTextAlignmentLeft;
    //时间输入框
    _tfTime = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, self.view.bounds.size.width - 130, 30)];
    _tfTime.placeholder = @"单行输入";
    _tfTime.borderStyle = UITextBorderStyleRoundedRect;
    
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    // 获取当前日期
//    NSDate* dt = [NSDate date];
//    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
//    unsigned unitFlags = NSCalendarUnitYear |
//    NSCalendarUnitMonth |  NSCalendarUnitDay |
//    NSCalendarUnitHour |  NSCalendarUnitMinute |
//    NSCalendarUnitSecond | NSCalendarUnitWeekday;
//    // 获取不同时间字段的信息
//    NSDateComponents* comp = [gregorian components: unitFlags
//                                          fromDate:dt];
//
//    _tfTime.text = [NSString stringWithFormat:@"%ld-%ld-%ld  星期%ld  %ld:%ld:%ld", comp.year, comp.month, comp.day, comp.weekday, comp.hour, comp.minute, comp.second];
    
    //定时器 反复执行
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    
    
    //设置为时间不可编辑
    [_tfTime resignFirstResponder];
    [_tfTime endEditing:YES];
    _tfTime.enabled = NO;
    
    //地点输入框
    _tfLocation = [[UITextField alloc] initWithFrame:CGRectMake(110, 60, self.view.bounds.size.width - 130, 30)];
    _tfLocation.placeholder = @"单行输入";
    _tfLocation.borderStyle = UITextBorderStyleRoundedRect;
    //景点名称输入框
    _tfScenicSports = [[UITextField alloc] initWithFrame:CGRectMake(110, 110, self.view.bounds.size.width - 130, 30)];
    _tfScenicSports.placeholder = @"单行输入";
    _tfScenicSports.borderStyle = UITextBorderStyleRoundedRect;
    //心得输入框
    _tvExperience = [[UITextView alloc] initWithFrame:CGRectMake(110, 160, self.view.bounds.size.width - 130, 200)];
    _tvExperience.layer.borderWidth = 1;
    _tvExperience.layer.borderColor = [[UIColor colorWithRed:128/255 green:128/255 blue:128/255 alpha:0.1] CGColor];
    _tvExperience.layer.cornerRadius = 5;
    _tvExperience.font = [UIFont systemFontOfSize:17];
    _tvExperience.delegate = self;
    //心得框的多行输入提示，使用代理
    _label = [[UILabel alloc] initWithFrame:CGRectMake(5, 4, 80, 20)];
    _label.enabled = NO;
    _label.text = @"多行输入";
    _label.font = [UIFont systemFontOfSize:17];
    _label.textColor = [UIColor colorWithRed:225/255 green:225/255 blue:225/255 alpha:0.05];
    [_tvExperience addSubview:_label];
    
    [self.view addSubview:_lbTime];
    [self.view addSubview:_lbLocation];
    [self.view addSubview:_lbScenicSpots];
    [self.view addSubview:_lbExperience];
    [self.view addSubview:_lbPictures];
    [self.view addSubview:_tfTime];
    [self.view addSubview:_tfLocation];
    [self.view addSubview:_tfScenicSports];
    [self.view addSubview:_tvExperience];
    
    
    //照片栏
    _svPictures = [[UIScrollView alloc] init];
    _svPictures.frame = CGRectMake(11, 410, self.view.bounds.size.width, 300);
    _svPictures.contentSize = CGSizeMake(self.view.bounds.size.width, 300);
    //不显示栏
    _svPictures.showsVerticalScrollIndicator = NO;
    //_svPictures.backgroundColor = [UIColor redColor];
    
    for(int i = 0; i < 6; i++) {
        if(i < 5) {
            _image[i] = [UIImage imageNamed:[NSString stringWithFormat:@"addPicture.png"]];
            //修改图片大小
            UIGraphicsBeginImageContext(CGSizeMake(_image[i].size.width*2, _image[i].size.height*2));
            [_image[i] drawInRect:CGRectMake((_image[i].size.width*2 - 32)/2, (_image[i].size.height*2 - 32)/2, 32, 32)];
            UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            _iView[i] = [[UIImageView alloc] initWithImage:reSizeImage];
            _iView[i].frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
            _iView[i].backgroundColor = [UIColor grayColor];
            [_svPictures addSubview:_iView[i]];
        }
        else {
            UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"add.png"]];
            //修改图片大小
            UIGraphicsBeginImageContext(CGSizeMake(image.size.width*2, image.size.height*2));
            [image drawInRect:CGRectMake((image.size.width*2 - 32)/2, (image.size.height*2 - 32)/2, 32, 32)];
            UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            UIImageView * iView = [[UIImageView alloc] initWithImage:reSizeImage];
            iView.frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
            iView.backgroundColor = [UIColor grayColor];
            
            iView.contentMode = UIViewContentModeCenter;
            iView.clipsToBounds = YES;
            [_svPictures addSubview:iView];
            
            //开启交互模式
            iView.userInteractionEnabled = YES;
            //创建点击手势
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pressTap:)];
            //单次点击
            tap.numberOfTapsRequired = 1;
            //单个手指
            tap.numberOfTouchesRequired = 1;
            
            [iView addGestureRecognizer:tap];
            
            //图像对象的tag值
            iView.tag = 101 + i;
            
        }
        
    }
    [self.view addSubview:_svPictures];
    
    
    //添加发布按钮
    UIBarButtonItem * btnPublish = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStyleDone target:self action:@selector(pressPublish)];
    self.navigationItem.rightBarButtonItem = btnPublish;
    
    
}

//UITextViewDelegate代理函数的实现
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    //开始编辑调用
    NSLog(@"textView开始编辑");
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
    //textView改变的时候调用3333
    if ([textView.text length] == 0) {
        [_label setHidden:NO];
    }else{
        [_label setHidden:YES];
    }
}


-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //回收键盘对象
    [_tfTime resignFirstResponder];
    [_tfLocation resignFirstResponder];
    [_tfScenicSports resignFirstResponder];
    [_tvExperience resignFirstResponder];
}

//add.png点击事件
-(void) pressTap : (UITapGestureRecognizer *) tap {
    NSLog(@"加载图片");
    VCPictureWall * pictureWall = [[VCPictureWall alloc] init];
    pictureWall.delegate = self;
    [self.navigationController pushViewController:pictureWall animated:YES];
}

//实现代理，获取参数
-(void) getPictureNum:(NSInteger *)pictureNum getPictureCount:(NSInteger)pictureCount {
    NSLog(@"得参");
    for(int i = 0; i < pictureCount; i++) {
        _pictureNum[i] = pictureNum[i];
    }
    _pictureCount = pictureCount;
    
    NSInteger count = _pictureCount;
    for(int i = 0; i < 5; i++) {
        if(count > 0) {
            _image[i] = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg", _pictureNum[i]]];
            _iView[i] = [[UIImageView alloc] initWithImage:_image[i]];
            _iView[i].frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
            _iView[i].contentMode = UIViewContentModeScaleToFill;
            _iView[i].clipsToBounds = YES;
            _iView[i].backgroundColor = [UIColor grayColor];
            [_svPictures addSubview:_iView[i]];
            
            count --;
        }
        else {
            _image[i] = [UIImage imageNamed:[NSString stringWithFormat:@"addPicture.png"]];
            //修改图片大小
            UIGraphicsBeginImageContext(CGSizeMake(_image[i].size.width*2, _image[i].size.height*2));
            [_image[i] drawInRect:CGRectMake((_image[i].size.width*2 - 32)/2, (_image[i].size.height*2 - 32)/2, 32, 32)];
            UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            _iView[i] = [[UIImageView alloc] initWithImage:reSizeImage];
            _iView[i].frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
            _iView[i].backgroundColor = [UIColor grayColor];
            [_svPictures addSubview:_iView[i]];
        }
        
        //        UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg", _pictureNum[i]]];
        //        UIImageView *iView = [[UIImageView alloc] initWithImage:image];
        //        iView.frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
        //        iView.contentMode = UIViewContentModeScaleToFill;
        //        iView.clipsToBounds = YES;
        //        iView.backgroundColor = [UIColor colorWithRed:128/255 green:128/255 blue:128/255 alpha:0.1];
        //        [_svPictures addSubview:iView];
        
    }
    
}


//发布事件函数
-(void) pressPublish {

    if(_tfTime.text.length == 0 || _tfLocation.text.length == 0 || _tfScenicSports.text.length == 0 || _tvExperience.text.length == 0) {
        UIAlertAction * OK = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
        if(_tfTime.text.length == 0) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"时间未填写!" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:OK];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else if(_tfLocation.text.length == 0) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"地点未填写!" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:OK];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else if (_tfScenicSports.text.length == 0) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"景点名称未填写!" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:OK];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else if (_tvExperience.text.length == 0) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"心得未填写!" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:OK];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
    }
    else {
        //添加全局变量
        AppDelegate * myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [myDelegate.time addObject:_tfTime.text];
        [myDelegate.location addObject:_tfLocation.text];
        [myDelegate.scenicSpots addObject:_tfScenicSports.text];
        [myDelegate.experience addObject:_tvExperience.text];
        NSMutableArray * array = [[NSMutableArray alloc] init];
        for(int i = 0; i < _pictureCount; i++) {
            NSString * str = [[NSString alloc] initWithFormat:@"%ld", _pictureNum[i]];
            [array addObject:str];
        }
        [myDelegate.pictureNums addObject:array];
        
        
        
        myDelegate.publishTimes ++ ;
        
        [myDelegate.tableView reloadData];
        
        //发布成功的弹窗，持续时间0.5s
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"发布成功！" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction:) userInfo:alertController repeats:NO];
        
        for(int i = 0; i < _pictureCount; i ++) {
            _image[i] = [UIImage imageNamed:[NSString stringWithFormat:@"addPicture.png"]];
            //修改图片大小
            UIGraphicsBeginImageContext(CGSizeMake(_image[i].size.width*2, _image[i].size.height*2));
            [_image[i] drawInRect:CGRectMake((_image[i].size.width*2 - 32)/2, (_image[i].size.height*2 - 32)/2, 32, 32)];
            UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            _iView[i] = [[UIImageView alloc] initWithImage:reSizeImage];
            _iView[i].frame = CGRectMake((i%3)*(15+120), (i/3)*(15+120), 120, 120);
            _iView[i].backgroundColor = [UIColor grayColor];
            [_svPictures addSubview:_iView[i]];
            
        }
        
        //_tfTime.text = @"";
        
        _tfLocation.text = @"";
        _tfScenicSports.text = @"";
        _tvExperience.text = @"";
        for(int i = 0; i < _pictureCount; i++) {
            _pictureNum[i] = 0;
        }
        _pictureCount = 0;
        
        //心得框的多行输入提示，使用代理
        _label = [[UILabel alloc] initWithFrame:CGRectMake(5, 4, 80, 20)];
        _label.enabled = NO;
        _label.text = @"多行输入";
        _label.font = [UIFont systemFontOfSize:17];
        _label.textColor = [UIColor colorWithRed:225/255 green:225/255 blue:225/255 alpha:0.5];
        [_tvExperience addSubview:_label];
    }
    
}

-(void)timerAction:(NSTimer *) timer {
    UIAlertController * alert = (UIAlertController *)[timer userInfo];
    [alert dismissViewControllerAnimated:YES completion:nil];
    alert = nil;
    
    AppDelegate * myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [myDelegate.tableView reloadData];
    self.tabBarController.selectedIndex = 0;
    //[self.navigationController popViewControllerAnimated:YES];
}

//更新时间
-(void)updateTime{
    NSDate *currentDate = [NSDate date];
    
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc]init];
    
    [dataFormatter setDateFormat:@"YYYY - MM - dd   HH : mm : ss "];
    
    NSString *dateString = [dataFormatter stringFromDate:currentDate];
    NSLog(@"%@",dateString);
    
    _tfTime.text = dateString;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
